package cn.kgc.springcloud.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.kgc.springcloud.clients.TagClient;
import cn.kgc.springcloud.entity.Clazz;
import cn.kgc.springcloud.entity.Tag;
import cn.kgc.springcloud.mapper.ClazzMapper;
import cn.kgc.springcloud.service.ClazzService;
import cn.kgc.springcloud.vo.ClazzVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author mengshun
* @description 针对表【t_clazz】的数据库操作Service实现
* @createDate 2025-01-17 09:31:07
*/
@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService{

    @Resource
    private TagClient tagClient;
    @Override
    public List<ClazzVO> clazzList() {

        List<Clazz> clazzes = baseMapper.selectList(null);
        List<ClazzVO> clazzVOS = clazzes.stream().map(clazz -> {
            ClazzVO clazzVO = new ClazzVO();
            BeanUtils.copyProperties(clazz, clazzVO);

            Integer tagid = clazz.getTagid();
            // 发送http请求获取标签信息
            Tag tag = tagClient.getTagById(tagid);
            clazzVO.setTag(tag);
            return clazzVO;
        }).collect(Collectors.toList());


        return clazzVOS;
    }

    @Override
    public boolean addClazz(MultipartFile file, String name, Integer tagId) {

        // 文件上传
        if (file.isEmpty()){
            throw  new RuntimeException("文件不能为空");
        }

        String originalFilename = file.getOriginalFilename();
        String filenameExtension = StringUtils.getFilenameExtension(originalFilename);
        // 文件路径
        String uuid = IdUtil.simpleUUID();
        String finalName = uuid+"."+filenameExtension;

        // 上传文件
        File f = new File("D:/upload/springcloud", finalName);
        try {
            file.transferTo(f);

            //添加班级信息到clazz表
            Clazz clazz = new Clazz();
            clazz.setName(name);
            clazz.setPath(finalName);
            clazz.setTagid(tagId);
            baseMapper.insert(clazz);
            return  true;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public boolean removeClazzById(Integer id, String logo) {

        File f = new File("D:/upload/springcloud", logo);
        if (f.exists()){
            f.delete();
        }

        baseMapper.deleteById(id);

        return true;
    }
}




